package com.example.questionnaire.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.common.utils.Constant;
import com.example.questionnaire.dto.AddMToTDto;
import com.example.questionnaire.dto.RemoveMFromTDto;
import com.example.questionnaire.dto.UserAddDto;
import com.example.questionnaire.entity.*;
import com.example.questionnaire.service.UserAnswererService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.example.questionnaire.service.UserService;
import com.example.common.utils.PageUtils;
import com.example.common.utils.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 *
 *
 * @author hsz
 * @email 1416446590@qq.com
 * @date 2022-10-29 09:51:04
 */
@Api("用户管理(包含租户、用户两种角色)")
@CrossOrigin
@RestController
@RequestMapping("questionnaire/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserAnswererService userAnswererService;
    @Autowired
    private HttpServletRequest haihaihia;
    @ApiOperation(value = "获取注册信息，进行注册操作")
    @PostMapping("/reg")
    public  R reg (@RequestBody UserEntity user){
        user.setExpense(new BigDecimal(0.0));
        int result = userService.reg(user);
        if (result == 0){
            return R.error(1,"账号已存在");
        }else if(result == 2){
            return R.error(4,"手机号已存在");
        }
        else{
            return R.ok("注册成功");
        }
    }

    @GetMapping("/login")
    public R login(@RequestParam(value = "username", required = false) String username, @RequestParam(value = "password", required = false) String password) {

        int result = userService.login(username, password);

        if (result == 2) {
            return R.error(2, "账号不存在");
        } else if (result == 3) {
            return R.error(3, "密码错误");
        } else if(result == 10){
            return R.error(10, "没有登录权限");
        }

        else {
            UserEntity user = userService.findByUsername(username);
            return R.ok().put("data", user);

        }
    }

    @ApiOperation(value = "获取手机验证码接口")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "telephone", value = "电话号码"),

    })
    @GetMapping("/getCode")
    public R getCode(@RequestParam(value = "telephone", required = false) String telephone, HttpSession session) {

        UserEntity result = userService.findByTelephone(telephone);

        if(result == null){
            return R.error(4,"该手机号还未注册");
        }
        String code = userService.getVcode(telephone);
        haihaihia.getServletContext().setAttribute("tele",telephone);
        haihaihia.getServletContext().setAttribute("code",code);
//        session.setAttribute("tele",telephone);
//        session.setAttribute("code",code);
//        session.setMaxInactiveInterval(300);

        Map<String, Object> map = new HashMap<>();
        map.put("vcode",code);
        map.put("data",result);
        return R.ok(map);
    }

    @ApiOperation(value = "通过手机验证码登录接口")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "telephone", value = "电话号码"),
            @ApiImplicitParam(name = "code", value = "验证码"),
    })
    @GetMapping("/loginByTelephone")
    public R loginByTele(@RequestParam(value = "telephone", required = false) String telephone,
                         @RequestParam(value = "code", required = false) String code,
                         HttpServletRequest request) {
//        HttpSession session = request.getSession();
//        Object tele = session.getAttribute("tele");
//        Object c = session.getAttribute("code");
        Object tele=haihaihia.getServletContext().getAttribute("tele");
        Object c=haihaihia.getServletContext().getAttribute("code");
        if (c == null){
            return R.error(6,"验证码已失效");
        }else if(!String.valueOf(tele).equals(telephone) || !String.valueOf(c).equals(code)){

            return R.error(7,"验证码错误");
        }
        UserEntity result = userService.findByTelephone(telephone);
        return R.ok().put("data",result);
    }

    @ApiOperation(value = "通过手机验证码找回密码接口")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "telephone", value = "电话号码"),
            @ApiImplicitParam(name = "code", value = "验证码"),
            @ApiImplicitParam(name = "password", value = "设置密码"),
    })
    @GetMapping("/findPassword")
    public R findPassword(@RequestParam(value = "telephone", required = false) String telephone,
                          @RequestParam(value = "code", required = false) String code,
                          @RequestParam(value = "password", required = false) String password,
                          HttpServletRequest request) {
//        HttpSession session = request.getSession();
//        Object tele = session.getAttribute("tele");
//        Object c = session.getAttribute("code");
        Object tele = haihaihia.getServletContext().getAttribute("tele");
        Object c = haihaihia.getServletContext().getAttribute("code");
        if (c == null) {
            return R.error(6, "验证码已失效");
        } else if (!String.valueOf(tele).equals(telephone)) {
            return R.error(7, "验证码错误");
        }
        int result = userService.findPassword(telephone, password);
        if (result != 1) {
            return R.error(8, "修改失败，重试");
        }
        return R.ok().put("data", userService.findByTelephone(telephone));
    }
    @ApiOperation(value = "修改用户权限")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "username", value = "用户名"),
    })
    @GetMapping("/setLoginAuth")
    public R setLoginAuth(@RequestParam(value = "username", required = false) String username){
        userService.setAuthority(username);
        return R.ok();
    }
    /**
     * 全部人员列表
     */
    @ApiOperation("查询(分页、模糊查询)一下三个参数，都封装到Map类型的params；返回值R{code:0,data:用户(全部人员,不包括答者)数组,msg:\"\"}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = "username", value = "模糊查询（支持用户名）username", paramType = "query", required = false,dataType = "String"),
            @ApiImplicitParam(name = "id", value = "当前界面操作人员的id号", paramType = "query", required = true,dataType = "int")
    })
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = userService.queryPage(params);

        return R.ok().put("data", page);
    }

    /**
     *   显示超级管理员列表
     */
    @ApiOperation("查询(分页、模糊查询)一下三个参数，都封装到Map类型的params；返回值R{code:0,data:用户(超级管理员)数组,msg:\"\"}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = "username", value = "模糊查询（支持用户名）username", paramType = "query", required = false,dataType = "String"),
            @ApiImplicitParam(name = "id", value = "当前界面操作人员的id号", paramType = "query", required = true,dataType = "int"),
    })
    @GetMapping("/list1")
    public R list1(@RequestParam Map<String,Object>params){
        PageUtils page = userService.queryPage1(params);
        return R.ok().put("data",page);
    }

    /**
     *  显示租户列表
     */
    @ApiOperation("查询(分页、模糊查询)一下三个参数，都封装到Map类型的params；返回值R{code:0,data:用户(租户)数组,msg:\"\"}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = "username", value = "模糊查询（支持用户名）username", paramType = "query", required = false,dataType = "String"),
            @ApiImplicitParam(name = "id", value = "当前界面操作人员的id号", paramType = "query", required = true,dataType = "int"),
    })
    @GetMapping("/list2")
    public R list2(@RequestParam Map<String,Object>params){
        PageUtils page = userService.queryPage2(params);
        return R.ok().put("data",page);
    }



    /**
     *  显示用户列表
     */
    @ApiOperation("查询(分页、模糊查询)一下三个参数，都封装到Map类型的params；返回值R{code:0,data:用户(用户)数组,msg:\"\"}")
    @ApiImplicitParams({
            @ApiImplicitParam(name =  Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = "username", value = "模糊查询（支持用户名）username", paramType = "query", required = false,dataType = "String"),
            @ApiImplicitParam(name = "id", value = "当前界面操作人员的id号", paramType = "query", required = true,dataType = "int"),
    })
    @GetMapping("/list3")
    public R list3(@RequestParam Map<String,Object>params){
        PageUtils page = userService.queryPage3(params);
        return R.ok().put("data",page);
    }

    /**
     *  显示答者列表
     */
    @ApiOperation("查询(分页、限制、模糊查询、id号)四个参数，都封装到Map类型的params；返回值R{code:0,data:答者数组,msg:\"\"}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = "id", value = "当前界面操作人员的id号", paramType = "query", required = true,dataType = "int"),
    })
    @GetMapping("/list4")
    public R list4(@RequestParam Map<String,Object>params){
        PageUtils page = userAnswererService.queryUserAnswerer(params);
        return R.ok().put("data",page);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id){
        UserEntity user = userService.getById(id);

        return R.ok().put("data", user);
    }

    /**
     * 添加user信息
     */
    @ApiOperation("(添加用户信息)")
    @PostMapping("/add")
    public R addUserInfo(@RequestBody UserAddDto userAddDto){
        int result1 = userService.addUserInfo(userAddDto);
        int result2 = userService.addUserTeamInfo(userAddDto);
        if(result1==1 || result2==1) {
            return R.ok();
        }else if(result1==2 || result2==2){
            return R.error(2,"用户名已经存在");
        }
        return R.ok();
    }

    /**
     * 删除user信息
     */
    @ApiOperation("(删除用户信息,1个参数id(用户实体类对象)")
    @ApiImplicitParams({
            @ApiImplicitParam(name ="user" , value = "用户", paramType = "delete", required = true,dataType = "UserEntity")
    })
    @PostMapping("/delete")
    public R delUserInfoById(@RequestBody UserEntity user){
        int i = userService.delUserInfoById(user);
//        完善无数据关联的用户、无数据关联的租户
        if(i==3){
            return R.error("该用户存在其他数据关联,不可删除");
        }
        return R.ok();
    }

    /**
     *修改用户信息
     */
    @ApiOperation("(更新修改用户信息,1个参数userEntity(用户实体类对象)")
    @ApiImplicitParams({
            @ApiImplicitParam(name ="userEntity" , value = "用户实体类对象", paramType = "update", required = true,dataType = "UserEntity")
    })
    @PostMapping("/update")
    public R modifyUserInfo(@RequestBody UserEntity userEntity){
        userService.modifyUserInfo(userEntity);
        return R.ok().put("data",userEntity);
    }
    /**
     *添加用户到群组
     */
    @ApiOperation("(测试通过)添加用户到群组")
    @ApiImplicitParams({
            @ApiImplicitParam(name ="AddMToTDto" , value = "用户/答者id+群组实体各个属性，群组使用sign、teamId"),
    })
    @PostMapping("/addMToT")
    public R addMToT(@RequestBody AddMToTDto addMToTDto){
        Integer memberId= addMToTDto.getMemberId();
        TeamEntity teamEntity = new TeamEntity();
        BeanUtils.copyProperties(addMToTDto,teamEntity);
        userService.addMToT(memberId,teamEntity);
        return R.ok().put("data",addMToTDto);
    }

    /**
     *从群组中移除用户
     */
    @ApiOperation("(测试通过)从群组中移除用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name ="RemoveMFromTDto" , value = "用户/答者id+群组实体各个属性，群组使用sign、teamId"),
    })
    @PostMapping("/removeMFromT")
    public R removeMFromT(@RequestBody RemoveMFromTDto removeMFromTDto){
        Integer memberId= removeMFromTDto.getMemberId();
        TeamEntity teamEntity = new TeamEntity();
        BeanUtils.copyProperties(removeMFromTDto,teamEntity);
        userService.removeMFromT(memberId,teamEntity);
        return R.ok().put("data",removeMFromTDto);
    }
//    /**
//     * 根据用户名精准查询(用户,租户)
//     */
//    @ApiOperation("(模糊查询用户信息,1个参数是用户的用户名")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name ="username" , value = "username", paramType = "query", required = true,dataType = "String")
//    })
//    @GetMapping("/query")
//    public R queryByUserName(@RequestParam Map<String, Object> params ){
//        PageUtils page=userService.queryByUserName(params);
//        return R.ok().put("data", page);
//    }
//    /**
//     * 修改
//     */
//    @RequestMapping("/update")
//    public R update(@RequestBody UserEntity user){
//		userService.updateById(user);
//
//        return R.ok();
//    }
//    /**
//     * 删除
//     */
//    @RequestMapping("/delete")
//    public R delete(@RequestBody Integer[] ids){
//		userService.removeByIds(Arrays.asList(ids));
//
//        return R.ok();
//    }
    /*
     *
     */
    /**
     * 租户下的用户的群组列表
     */
    @ApiOperation("查询(分页、模糊、id查询)(根据user.id标识符查询，能够查出该租户下所有群组)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params",  paramType = "Map<String, Object>")
    })
    @GetMapping("/ttList")
    public R tenantTeamList(@RequestParam Map<String, Object> params){
        PageUtils page = userService.queryTeamPage(params);

        return R.ok().put("data", page);
    }

    /**
     * 租户下的用户的问卷列表
     */
    @ApiOperation("查询(分页、模糊、id查询)(根据user.id标识符查询，能够查出该租户下所有用户的问卷)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params",  paramType = "Map<String, Object>")
    })
    @GetMapping("/tqList")
    public R tenantQuestionnaireList(@RequestParam Map<String, Object> params){
        PageUtils page = userService.queryTenantQuestionnairePage(params);
        return R.ok().put("data", page);
    }

    /**
     * 查询租户下未进入群组的用户
     */
    @ApiOperation("(测试通过)查询名下未进入群组的用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",  paramType = "Integer"),
            @ApiImplicitParam(name = "teamId",  paramType = "Integer")
    })
    @GetMapping("/queryMNoInT")
    public R queryUNoInT(@RequestParam Map<String, Object> params){
        PageUtils page = userService.queryMNoInT(params);
        return R.ok().put("data", page);
    }
    /**
     * 用户对自己发布的某一问卷的答卷结果进行数据分析
     */
    @ApiOperation("饼图数据分析(传入问卷的questionnaireId和problemId即可)")
    @GetMapping("/analysis")
    public R analysis(@RequestParam(value = "questionnaireId", required = false) Integer questionnaireId) {
        List<PieEntity>pieEntities= userService.analysis(questionnaireId);
        List<List<PieDisplayEntity>>listTotal=new ArrayList<>();
        for(int i=0;i<pieEntities.size();i++) {
            PieEntity pieEntity=pieEntities.get(i);
            String option1 = pieEntity.getOption1();
            Integer number1 = pieEntity.getNumber1();
            String option2 = pieEntity.getOption2();
            Integer number2 = pieEntity.getNumber2();
            String option3 = pieEntity.getOption3();
            Integer number3 = pieEntity.getNumber3();
            String option4 = pieEntity.getOption4();
            Integer number4 = pieEntity.getNumber4();
            PieDisplayEntity pieDisplayEntity1 = new PieDisplayEntity();
            pieDisplayEntity1.setValue(number1);
            pieDisplayEntity1.setName(option1);
            PieDisplayEntity pieDisplayEntity2 = new PieDisplayEntity();
            pieDisplayEntity2.setValue(number2);
            pieDisplayEntity2.setName(option2);
            PieDisplayEntity pieDisplayEntity3 = new PieDisplayEntity();
            pieDisplayEntity3.setValue(number3);
            pieDisplayEntity3.setName(option3);
            PieDisplayEntity pieDisplayEntity4 = new PieDisplayEntity();
            pieDisplayEntity4.setValue(number4);
            pieDisplayEntity4.setName(option4);
            List<PieDisplayEntity> list = new ArrayList<>();
            list.add(pieDisplayEntity1);
            list.add(pieDisplayEntity2);
            list.add(pieDisplayEntity3);
            list.add(pieDisplayEntity4);
            listTotal.add(list);
        }
        return R.ok().put("data", listTotal);
    }

    /**
     * 用户对自己发布的某一问卷的答卷结果进行数据分析
     */
    @ApiOperation("柱状图数据分析(传入问卷的questionnaireId和problemId即可)")
    @GetMapping("/analysis1")
    public R analysis1(@RequestParam(value = "questionnaireId", required = false) Integer questionnaireId) {
        List<PieEntity>pieEntities= userService.analysis(questionnaireId);
        List<BarDisplayEntity>listTotal=new ArrayList<>();
        for(int i=0;i<pieEntities.size();i++) {
            PieEntity pieEntity=pieEntities.get(i);
            String option1 = pieEntity.getOption1();
            Integer number1 = pieEntity.getNumber1();
            String option2 = pieEntity.getOption2();
            Integer number2 = pieEntity.getNumber2();
            String option3 = pieEntity.getOption3();
            Integer number3 = pieEntity.getNumber3();
            String option4 = pieEntity.getOption4();
            Integer number4 = pieEntity.getNumber4();
            BarDisplayEntity barDisplayEntity = new BarDisplayEntity();
            barDisplayEntity.setxAxis(new String[]{option1, option2, option3, option4});
            barDisplayEntity.setSeries(new Integer[]{number1, number2, number3, number4});
            listTotal.add(barDisplayEntity);
        }
        return R.ok().put("data", listTotal);
    }
}

